package drds.data_propagate.driver.packets.client.command_packet;

import drds.data_propagate.driver.packets.CommandPacket;
import drds.data_propagate.driver.utils.ByteHelper;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * COM_BINLOG_DUMP
 */
public class BinlogDumpPacket extends CommandPacket {

    /**
     * BINLOG_DUMP options
     */
    public static final int BINLOG_DUMP_NON_BLOCK = 1;
    public static final int BINLOG_SEND_ANNOTATE_ROWS_EVENT = 2;
    @Setter
    @Getter
    public long binlogPosition;
    @Setter
    @Getter
    public long slaveServerId;
    @Setter
    @Getter
    public String binlogFileName;

    public BinlogDumpPacket() {
        setCommand((byte) 0x12);
    }

    public void decode(byte[] bytes) {
        // bypass
    }

    /**
     * <pre>
     * Bytes                        Name
     *  -----                        ----
     *  1                            command
     *  n                            arg
     *  --------------------------------------------------------
     *  Bytes                        Name
     *  -----                        ----
     *  4                            binlog_event position to start at (little endian)
     *  2                            binlog_event flags (currently not used; always 0)
     *  4                            server_id of the slave (little endian)
     *  n                            binlog_event file name (optional)
     *
     * </pre>
     */
    public byte[] encode() throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // 0. write command number
        byteArrayOutputStream.write(getCommand());
        // 1. write 4 bytes bin-log position to start at
        ByteHelper.writeUnsignedIntLittleEndian(binlogPosition, byteArrayOutputStream);
        // 2. write 2 bytes bin-log flags
        int binlog_flags = 0;
        binlog_flags |= BINLOG_SEND_ANNOTATE_ROWS_EVENT;
        byteArrayOutputStream.write(binlog_flags);
        byteArrayOutputStream.write(0x00);
        // 3. write 4 bytes server id of the slave
        ByteHelper.writeUnsignedIntLittleEndian(this.slaveServerId, byteArrayOutputStream);
        // 4. write bin-log file name if necessary
        if (StringUtils.isNotEmpty(this.binlogFileName)) {
            byteArrayOutputStream.write(this.binlogFileName.getBytes());
        }
        return byteArrayOutputStream.toByteArray();
    }

}
